package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.RoleDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {
    @Autowired
    RoleDao roleDao;


    @Override
    public void add(Integer[] permissionIds, Integer[] menuIds, Role role) {
        roleDao.add(role);
        setRoleAndPerMission(role.getId(),permissionIds);
        setRoleAndMenu(role.getId(),menuIds);
    }

    private void setRoleAndPerMission(Integer roleId, Integer[] permissionIds) {
        if(roleId != null && permissionIds !=null && permissionIds.length>0){
            for (Integer permissionId : permissionIds) {
                roleDao.setRoleAndPerMission(roleId,permissionId);

            }
    }
    }

    private void setRoleAndMenu(Integer roleId, Integer[] menuIds) {
        if (roleId != null && menuIds != null && menuIds.length > 0) {
            for (Integer menuId : menuIds) {
                roleDao.setRoleAndMenu(roleId, menuId);

            }
        }
    }
    @Override
    public PageResult queryByCondition(Integer currentPage, String queryString, Integer pageSize) {
        PageHelper.startPage(currentPage,pageSize);
        Page<Role> page=roleDao.queryByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public Role findById(Integer id) {
        return roleDao.findById(id);
    }

    @Override
    public List<Integer> findPermissionByRoleId(Integer id) {
        return roleDao.findPermissionByRoleId(id);
    }

    @Override
    public List<Integer> findMenuByRoleId(Integer id) {
        return roleDao.findMenuByRoleId(id);
    }

    @Override
    public void edit(Integer[] permissionIds, Integer[] menuIds, Role role) {
        //修改角色基本信息
        roleDao.update(role);
        //删除角色与权限关联
        roleDao.deleteRoleandPermissionAssociation(role.getId());
        //删除角色与菜单关联
        roleDao.deleteRoleandMenuAssociation(role.getId());
        //添加新关系
        setRoleAndPerMission(role.getId(),permissionIds);
        setRoleAndMenu(role.getId(),menuIds);
    }

    @Override
    public void delete(Integer id) {
        //删除角色与权限关联
        roleDao.deleteRoleandPermissionAssociation(id);
        //删除角色与菜单关联
        roleDao.deleteRoleandMenuAssociation(id);
        roleDao.delete(id);

    }


}
